import simplejson
import traceback
from django.http import HttpResponse
from musiclink.models import MidLink

def data_import(request):
    """
    """
    try:
        data_json = request.POST['data_json']
        data_list = simplejson.loads(data_json)
        for data_item in data_list:
            # check by mid
            if MidLink.all().filter('mid =',data_item['mid']).count() != 0:
                continue
            # check dup by name and singer
            if MidLink.all().filter('name =',data_item['name']).\
                    filter('singer =',data_item['singer']).count() != 0:
                continue

            # create new
            ml = MidLink()
            ml.name = data_item['name']
            ml.singer = data_item['singer']
            if data_item.has_key('mid'):
                ml.mid = data_item['mid']
            if data_item.has_key('xid'):
                ml.mid = data_item['xid']
            if data_item.has_key('kid'):
                ml.mid = data_item['kid']
            if data_item.has_key('bid'):
                ml.mid = data_item['bid']
            ml.put()
        return HttpResponse(simplejson.dumps({'code':0}))
    except:
        return HttpResponse(simplejson.dumps({
            'code':1,
            'data':{
                'errorMessage':traceback.format_exc()
                }}))
